import os
import requests
from typing import List, Dict, Any


# 豆包大模型配置
DOUBAO_API_KEY = os.getenv("DOUBAO_API_KEY", "2f47aacd-c91a-4b3e-816e-7b766bc574b2")
DOUBAO_BASE_URL = os.getenv("DOUBAO_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3")
DOUBAO_MODEL = os.getenv("DOUBAO_MODEL", "doubao-1-5-thinking-pro-250415")


def generate_consultation_reply(message: str, history: List[Dict[str, Any]]) -> str:
    """Return LLM reply using Doubao if configured; otherwise provide a safe fallback.

    message: current user message
    history: optional chat history as a list of {role, content}
    """
    if not message:
        return "请描述您的症状、持续时间及伴随症状，我将为您提供初步建议。"

    if not DOUBAO_API_KEY:
        return (
            "[演示模式] 您的描述我已收到。建议：\n"
            "1) 若出现胸痛、呼吸急促、持续发热等，请尽快就医；\n"
            "2) 记录体温、心率、血压等指标；\n"
            "3) 若能提供更多既往史、用药史，我可给出更具体建议。"
        )

    try:
        payload = {
            "model": DOUBAO_MODEL,
            "messages": ([{"role": "system", "content": "你是专业的全科医生助理，输出简洁、准确、可操作。"}] + history + [{"role": "user", "content": message}]),
            "temperature": 0.2,
        }
        headers = {
            "Authorization": f"Bearer {DOUBAO_API_KEY}",
            "Content-Type": "application/json",
        }

        # 豆包API路径
        url = f"{DOUBAO_BASE_URL.rstrip('/')}/chat/completions"
        resp = requests.post(url, json=payload, headers=headers, timeout=30)
        resp.raise_for_status()
        data = resp.json()

        # OpenAI-compatible format
        choices = data.get("choices") or []
        if choices and "message" in choices[0]:
            return choices[0]["message"].get("content", "") or "(无内容)"

        # Fallback format
        if choices and "text" in choices[0]:
            return choices[0].get("text", "") or "(无内容)"

        return "(未获取到模型回复)"
    except Exception as e:
        return (
            f"[LLM暂不可用] 已记录您的问题。建议：\n"
            "- 如症状加重，及时前往线下医院；\n"
            "- 详细描述病程、既往史与用药史有助于更准确判断。\n"
            f"[错误: {str(e)}]"
        )


